<script setup lang="ts">
import { ref, unref } from 'vue'
import { without } from 'lodash-es'
import { Tag } from 'ant-design-vue'
import BasicModal from '@/components/Modal/src/BasicModal.vue'
import { BasicForm, useForm } from '@/components/Form'
import { moduleScopeFormSchema } from '@/views/sys/role/role.data'
import { useModalInner } from '@/components/Modal'
import type { CheckKeys, CheckedEvent, TreeItem } from '@/components/Tree'
import { BasicTree } from '@/components/Tree'
import { moduleApi } from '@/api/sys/moduleApi'
import { roleApi } from '@/api/sys/roleApi'

defineOptions({ name: 'RoleModuleScopeModal' })
const emit = defineEmits(['success', 'register'])
const treeData = ref<TreeItem[]>([])
const treeRef = ref()
// 默认展开的层级
const defaultExpandLevel = ref<number>(1)
const parentIdSets = ref<Set<string>>(new Set())
const moduleKeys = ref<string[]>([])
const moduleHalfKeys = ref<string[]>([])

const [registerForm, { setFieldsValue, validate }] = useForm({
  labelWidth: 120,
  baseColProps: { span: 24 },
  schemas: moduleScopeFormSchema,
  showActionButtonGroup: false,
  actionColOptions: { span: 23 },
})
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  menuReset()
  setModalProps({ confirmLoading: false })
  if (unref(treeData).length === 0) {
    const list = (await moduleApi.list()).rows
    treeData.value = (await moduleApi.tree()).rows
    // 去重 拿到所有的父节点
    parentIdSets.value = new Set(list.map(item => item.parentModuleId))
  }
  const role = { ...unref(data.record) }
  const moduleIdList = (await roleApi.modules({ roleId: role.roleId })).rows.map(
    item => item.moduleId,
  )
  const excludeParentIds = without(moduleIdList, ...Array.from(parentIdSets.value))
  moduleKeys.value = moduleIdList
  role.moduleIdList = excludeParentIds
  await setFieldsValue({ ...role })
  // 默认展开的层级
  if (unref(treeRef))
    unref(treeRef).filterByLevel(defaultExpandLevel.value)
})

function menuReset() {
  moduleKeys.value = []
  moduleHalfKeys.value = []
}

function menuCheck(checkedKeys: CheckKeys, event: CheckedEvent) {
  if (Array.isArray(checkedKeys)) {
    // 这里是子节点的ID
    moduleKeys.value = checkedKeys as string[]
    // 这里是父节点的ID 默认空数组
    moduleHalfKeys.value = event.halfCheckedKeys?.map(x => `${x}`) as string[]
  }
}

async function handleSubmit() {
  try {
    const values = await validate()
    setModalProps({ confirmLoading: true })
    await roleApi.assignModules({
      roleId: values.roleId,
      moduleIdList: [...moduleKeys.value, ...moduleHalfKeys.value],
    })
    closeModal()
    emit('success')
  }
  finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>

<template>
  <BasicModal v-bind="$attrs" :min-height="200" title="功能权限" @register="registerModal" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #moduleIdList="{ model, field }">
        <BasicTree
          v-if="treeData.length"
          ref="treeRef"
          v-model:checkedKeys="model[field]"
          :tree-data="treeData"
          :field-names="{ title: 'moduleName', key: 'moduleId' }"
          toolbar
          checkable
          search
          :show-icon="true"
          :show-strictly-button="false"
          :selectable="false"
          @check="menuCheck"
        >
          <template #title="{ moduleName, moduleType }">
            {{ moduleName }}
            <Tag v-if="moduleType === 0" color="red">
              目录
            </Tag>
            <Tag v-else-if="moduleType === 1" color="green">
              菜单
            </Tag>
            <Tag v-else-if="moduleType === 2" color="blue">
              按钮/控件
            </Tag>
            <Tag v-else color="blue">
              接口
            </Tag>
          </template>
        </BasicTree>
      </template>
    </BasicForm>
  </BasicModal>
</template>
